// pages/newpage/newpage.js
var util = require("../../utils/util.js")
var api = require("../../utils/api.js")
var QQMapWX = require('../../utils/qqmap/qqmap-wx-jssdk.js');
let app = getApp();
var qqmapsdk;
let a = false;
let touchDotX = 0; //X按下时坐标
let touchDotY = 0; //y按下时坐标
let interval; //计时器
let time = 0; //从按下到松开共多少时间*100
Page({

    /**
     * 页面的初始数据
     */
    data: {
        nvabarData: {
            showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
            title: '巡河宝', //导航栏 中间的标题
        },
        height: app.globalData.height * 2 + 20,
        type: 4,
        province: '湖南省',
        city: '长沙市',
        latitude: '28.13551',
        longitude: '113.03555',
        keyinput: '长沙',
        gender: 1,
        nickname: "巡河宝用户",
        content: {
            usercount: 46,
            adv: {
                type: "single",
                ad: [{
                    image: "https://wntest.stw88.com/static/upload/28520db47edd5d45/98fdfc3dd3264c14.png",
                    link: "",
                    name: "1",
                    url: ""
                }]
            },
            worsecount: 33,
            goodscount: 100,
            rivercount: 24,
            msg: [{

                    type: "indexmsg",
                    contents: "陈先生新增了一条巡护",

                },
                {
                    type: "indexmsg",
                    contents: "石头新增了一个标记点",
                },
                {
                    type: "indexmsg",
                    contents: "陈先生新增了一条巡护",
                }
            ],
        },
        content2: '',
        uid: 0,
        time: '',
        autoplay: true,
        interval: 5000,
        duration: 500,
        groupmarks: [],
        newmarks: [{
            id: 33,
            intro: "河水虽浑浅清，岸线水边可清澈见底，裸露河床的滩涂，陈旧滞留垃圾较多，待到丰水季节，又不知漂到哪里去了…",
            photos: [
                "https://wntest.stw88.com/static/upload/weixin/20190201/9b5aa862feab6e6a1a60ad317fd6a072.jpg",
                "https://wntest.stw88.com/static/upload/weixin/20190201/9a75a4877903df0efd793a75307b5282.jpg",
                "https://wntest.stw88.com/static/upload/weixin/20190201/5d692b0898528199d134fade3798f29f.jpg",
                "https://wntest.stw88.com/static/upload/weixin/20190201/b41718fe2a52d4436ac9162d8f5adf87.jpg",
                "https://wntest.stw88.com/static/upload/weixin/20190201/2163f26ff35461eca0a1f3811a103dc9.jpg",
                "https://wntest.stw88.com/static/upload/weixin/20190201/6783e3a14e454899cb2d592ff90ab5ed.jpg"
            ],
            address: "栖凤路",
            river_state: "1",
            account_id: 311,
            rp_id: 232,
            longitude: "113.01191813151041",
            latitude: "28.24210693359375",
            follow: 6,
            view: 435,
            create_time: "2019-02-01 17:54:50",
            pid: 0,
            province: "湖南省",
            city: "长沙市",
            district: "开福区",
            ups: 8,
            comments: 7,
            score: "",
            hotpoint: "15",
            goods: "",
            wores: "",
            river_statename: "美好点",
            username: "狮山渔夫",
            cover: "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLxJgEJhfSxOaLc5BicUE2Z0vW8ARyEQ0san4TCCBUdRy32KSkGXd5zW7c2mc3fdz7qeLwjJfWv2SQ/132",
            upstate: 1,
            usercomments: [],
            upsuser: []
        }],
        page: 1,
        page1: 1,
        contentdata: {},
        world: '',
        world2: '',
        cruise: 0,
        width: '',
        height2: '',
        groupmarkslength: 0,
        floorstatus: false,
        countdown: 5,
        newmarkslength: 0,
        hotmarkslength: 0,
        sharearray: ['你想参与的河流保护行动在这里，快来看看！', '专属你的河流保护平台，汇集千万爱河流的人。', '河流保护必备神器--巡河宝邀您一起巡河']
    },
    getLocalt: function(latitude, longitude, city) {
        let vm = this;
        var data = {
            city: city,
            latitude: latitude,
            longitude: longitude,
            pages: 1
        }
        var url = app.u.H + app.u.river.GROUPLIST
        api.requestUrl(data, url).then(res => {
            if (res.code == 200) {
                wx.setStorage({
                    key: 'grouplist',
                    data: res.data
                })
            } else {}
        })

    },

    // 触摸开始事件
    touchStart: function(e) {
        touchDotX = e.touches[0].pageX; // 获取触摸时的原点
        touchDotY = e.touches[0].pageY;
    },
    // 触摸结束事件
    touchEnd: function(e) {

        let touchMoveX = e.changedTouches[0].pageX;
        let touchMoveY = e.changedTouches[0].pageY;
        let tmX = touchMoveX - touchDotX;
        let tmY = touchMoveY - touchDotY;
        if (time < 20) {
            let absX = Math.abs(tmX);
            let absY = Math.abs(tmY);
            if (absX > 2 * absY) {
                if (tmX < 0) {
                    this.show()
                } else {
                    this.show()
                }
            }
            if (absY > absX * 2 && tmY < 0) {
                this.show()
            }
        }

    },
    tableCheck: function(e) {
        var that = this
        that.setData({
            type: e.currentTarget.id
        })
    },
    bindKeyInput: function(e) {
        // console.log(e)
        // var that = this
        // that.setData({
        //     keyinput: e.currentTarget.dataset.name
        // })
        // console.log(e.currentTarget.dataset.name)
        wx.navigateTo({
            url: '../search/search',
        })
    },
    comments: function(e) {
        wx.navigateTo({
            url: '../comments/comments?id=' + e.currentTarget.id+'&index='+ e.currentTarget.dataset.index+'&marks='+ e.currentTarget.dataset.marks,
        })
    },
    cruisedetails2: function(e) {
        a = true
        var that = this
            // console.log(e)
        var src = e.currentTarget.dataset.src; //获取data-src
        var imgList = e.currentTarget.dataset.list; //获取data-list
        //图片预览
        // console.log(e.currentTarget.dataset.list)
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: imgList // 需要预览的图片http链接列表
        })
    },
    cruisedetails3: function(e) {
        a = true
        var that = this
            // console.log(e)
        var src = e.currentTarget.dataset.src; //获取data-src
        var imgList = e.currentTarget.dataset.list; //获取data-list
        //图片预览
        // console.log(e.currentTarget.dataset.list)
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: [imgList] // 需要预览的图片http链接列表
        })
    },
    cruisedetails: function(e) {
        var that = this
        wx.navigateTo({
            url: '../cruisedetails/cruisedetails?id=' + e.currentTarget.dataset.id + "&type=mark",
        })
    },
    index: function(e) {
        var that = this
        wx.navigateTo({
            url: '../index/index?state=' + e.currentTarget.dataset.state,
        })
    },
    give: function(e) {
        var that = this
        var data = {
            type: 'mark',
            id: e.currentTarget.id,
            account_id: wx.getStorageSync('userinfo').id
        }
        var url = app.u.H + app.u.river.UPSINDEX
        var dataups = 'hotmarks[' + e.currentTarget.dataset.index + '].ups'
        var userups = 'hotmarks[' + e.currentTarget.dataset.index + '].upstate'

        api.requestUrl(data, url).then(res => {
            // console.log(res)
            if (res.code == 200) {
                var ups = e.currentTarget.dataset.ups
                that.setData({
                    [dataups]: ups + 1,
                    [userups]: 1
                })
                api.showError(res.msg)
            } else {
                api.showError(res.msg)
            }
        })
    },
    newgive: function(e) {
        var that = this
        console.log(222)
        var data = {
            type: 'mark',
            id: e.currentTarget.id,
            account_id: wx.getStorageSync('userinfo').id
        }
        var url = app.u.H + app.u.river.UPSINDEX
        var dataups = 'newmarks[' + e.currentTarget.dataset.index + '].ups'
        var userups = 'newmarks[' + e.currentTarget.dataset.index + '].upstate'
        api.requestUrl(data, url).then(res => {
            if (res.code == 200) {
                var ups = e.currentTarget.dataset.ups
                that.setData({
                    [dataups]: ups + 1,
                    [userups]: 1
                })
            } else {
                api.showError(res.msg)
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        var that = this
        if (wx.getStorageSync('userinfo').id) {
            var data = {
                account_id: wx.getStorageSync('userinfo').id
            }
            var url = app.u.H + app.u.river.GETUSERINFO
            api.requestUrl(data, url).then(res => {
                if (res.code == 200) {
                    wx.setStorageSync("userinfo", res.data)
                }
            })
        }

        let isshow = wx.getStorageSync('isshow') || 0
        if (!isshow) {
            wx.setStorageSync('isshow', 1)
            wx.createSelectorQuery().select('.view-open').boundingClientRect((rect) => {
                that.setData({
                    height2: rect.height
                })
                var countdown = that.data.countdown
                timer: setInterval(function() {
                    if (countdown == 0) {
                        wx.showTabBar({
                            success: function(res) {
                                that.setData({
                                    cruise: 1
                                })
                                clearInterval(interval)
                            }
                        })
                        return;
                    } else {
                        countdown--;
                        that.setData({
                            countdown: countdown
                        })
                    }
                }, 1000)
            }).exec()
            wx.hideTabBar({})
        } else {
            that.setData({
                cruise: 1
            })
        }
        wx.getStorage({
            key: 'userinfo',
            success: function(res) {
                // console.log(res)
                that.setData({
                    nickname: res.data.nick_name,
                    gender: res.data.gender
                })
            }
        })
        var DATE = util.formatData(new Date());
        that.setData({
            time: DATE,
            // cruise: isshow,
        });
        qqmapsdk = new QQMapWX({
            key: 'TTWBZ-6L56U-W55V3-BJZJ6-KGGYF-O2BRB'
        })
        wx.getStorage({
            key: 'userinfo',
            success: function(res) {
                // console.log(res)
                that.setData({
                    nickname: res.data.nick_name,
                    gender: res.data.gender
                })
                wx.getLocation({
                    type: 'gcj02',
                    success: function(res) {
                        wx.setStorage({
                            key: 'localtion',
                            data: "1"
                        })
                        that.getLocal(res.latitude, res.longitude)
                            //that.getUserLocation()
                    },
                    fail: function() {
                        that.getUserLocation()
                    }
                })
            },
            fail: function(res) {
                wx.setStorage({
                    key: 'localtion',
                    data: "2"
                })
            }
        })
        qqmapsdk.geocoder({
            address: that.data.city, //用户输入的地址（注：地址中请包含城市名称，否则会影响解析效果），如：'北京市海淀区彩和坊路海淀西大街74号'
            complete: res => {
                console.log(1111)
                console.log(res.result.location); //经纬度对象
                wx.setStorageSync('address', res.result.location)
            }
        })

    },
    show: function() {
        var that = this
        wx.showTabBar({
            success: function(res) {
                that.setData({
                    cruise: 1
                })

            }
        })
    },
    getUserLocation: function() {
        let vm = this;
        wx.getSetting({
            success: (res) => {
                // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
                // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
                // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
                if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                    wx.showModal({
                        title: '请求授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function(res) {
                            if (res.cancel) {
                                wx.showModal({
                                    title: '定位失败',
                                    content: '请先允许“使用我的地理位置”后，再查看定位城市的信息，巡河宝默认展示地址为长沙',
                                    showCancel: false, //是否显示取消按钮
                                    confirmText: "确定",
                                })
                                vm.getLocal(vm.data.latitude, vm.data.longitude)
                            } else if (res.confirm) {
                                wx.openSetting({
                                    success: function(dataAu) {
                                        if (dataAu.authSetting["scope.userLocation"] == true) {
                                            wx.showToast({
                                                title: '授权成功',
                                                icon: 'success',
                                                duration: 1000
                                            })
                                            vm.getLocation();
                                        } else {
                                            wx.showModal({
                                                title: '定位失败',
                                                content: '请先允许“使用我的地理位置”后，再查看定位城市的信息，巡河宝默认展示地址为长沙',
                                                showCancel: false, //是否显示取消按钮
                                                confirmText: "确定",
                                            })
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else if (res.authSetting['scope.userLocation'] == undefined) {
                    //调用wx.getLocation的API
                    vm.getLocation();
                } else {
                    //调用wx.getLocation的API
                    vm.getLocation();
                }
            },
            fail: (res) => {
                vm.getLocation();
            }
        })
    },
    // 微信获得经纬度
    getLocation: function() {
        let vm = this;
        wx.getLocation({
            type: 'wgs84',
            success: function(res) {
                // console.log(JSON.stringify(res))
                var latitude = res.latitude
                var longitude = res.longitude
                vm.getLocal(latitude, longitude)
            },
            fail: function(res) {
                vm.getLocal(vm.data.latitude, vm.data.longitude)
            }
        })
    },
    getLocal: function(latitude, longitude) {
        let vm = this;
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: latitude,
                longitude: longitude
            },
            success: function(res) {
                let province = res.result.ad_info.province
                let city = res.result.ad_info.city
                    //存储群组信息
                vm.getLocalt(latitude, longitude, city)
                vm.setData({
                    province: province,
                    city: city,
                    latitude: latitude,
                    longitude: longitude,
                })
                wx.setStorageSync("usercity", city)
                wx.setStorageSync("userparent", province)
                vm.getindexinfo(province, city)
            },
            fail: function(res) {},
            complete: function(res) {
                // console.log(res);
            }
        });

    },
    getindexinfo: function(province, city) {
        let vm = this;
        //查询数据
        var data = {
            province: province,
            city: city,
            account_id: wx.getStorageSync('userinfo').id
        }
        var url = app.u.H + app.u.river.INDEXNEW
        api.requestUrl(data, url).then(res => {
            if (res.code == 200) {

                vm.setData({
                    newmarks: res.data.newmarks,
                    newmarkslength: res.data.newmarks.length,
                    hotmarks: res.data.hotmarks,
                    hotmarkslength: res.data.hotmarks.length,
                    content: res.data,
                    city: city
                })
                wx.hideLoading()
                var usercount = res.data.usercount
                wx.setStorageSync("usercount", usercount)

            }
        })
        var data2 = {
            city: city,
        }
        var url2 = app.u.H + app.u.river.GETWEATHER
        api.requestUrl(data2, url2).then(res => {
            // console.log(1111)
            // console.log(res.HeWeather6[0].now.cond_txt)
            wx.setStorageSync('cond_txt',res.HeWeather6[0].now.cond_txt)
            vm.setData({
                content2: res.HeWeather6[0]
            })
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        if (a) {
            a = false
            return
        }
        let that = this

        app.globalData.share = false
        var usercity = wx.getStorageSync('usercity')
        var userparent = wx.getStorageSync('userparent')
            // console.log(usercity)
            // console.log(userparent)
        let cityfresh = wx.getStorageSync('cityfresh') || 0
        if (usercity == '' && userparent == '') {

        } else if (cityfresh) {
            wx.setStorageSync('cityfresh', 0)
            that.getindexinfo(userparent, usercity)
        }
        let localtion = wx.getStorageSync('localtion') || 1
        if (localtion == 2) {
            wx.setStorageSync('localtion', 1)
            wx.getLocation({
                type: 'gcj02',
                success: function(res) {
                    wx.setStorage({
                        key: 'localtion',
                        data: "1"
                    })
                    that.getLocal(res.latitude, res.longitude)
                        //that.getUserLocation()
                },
                fail: function() {
                    that.getUserLocation()
                }
            })
        }
        let fresh = wx.getStorageSync('fresh') || 0
        if (fresh) {
            wx.setStorageSync('fresh', 0)
            let newpage = 1
            let data = {
                city: that.data.city,
                pages: newpage,
                account_id: wx.getStorageSync('userinfo').id
            }
            var url = app.u.H + app.u.river.SHOWNEWMARKS
            api.requestUrl(data, url).then(res => {
                if (res.code == 200) {
                    wx.pageScrollTo({
                        scrollTop: 100
                    })
                    that.setData({
                        newmarks: res.data,
                        page: newpage,
                        type: 4
                    })
                }
            })
        }
    },
    onReachBottom: function() {
        let that = this
        if (that.data.type == 4) {
            let newpage = that.data.page + 1
            let data = {
                city: that.data.city,
                pages: newpage,
                account_id: wx.getStorageSync('userinfo').id
            }
            var url = app.u.H + app.u.river.SHOWNEWMARKS
            api.requestUrl(data, url).then(res => {
                if (res.code == 200) {
                    that.setData({
                        newmarks: that.data.newmarks.concat(res.data),
                        page: newpage
                    })
                }
            })
        } else {
            let newpage1 = that.data.page1 + 1
            let data = {
                pages: newpage1,
                account_id: wx.getStorageSync('userinfo').id,
                id: wx.getStorageSync('userinfo').group_id,
                city: that.data.city,
            }
            var url = app.u.H + app.u.river.SHOWHOTMARKS
            api.requestUrl(data, url).then(res => {
                // console.log(99999)
                // console.log(res.data)
                if (res.code == 200) {

                    that.setData({
                            hotmarks: that.data.hotmarks.concat(res.data),
                            page1: newpage1
                        })
                        // api.showError(res.msg)
                } else {
                    api.showError(res.msg)
                }
            })
        }


    },
    onShareAppMessage: function(res) {
        var that = this
        let uid = wx.getStorageSync('userinfo').id
        let nickname = wx.getStorageSync('userinfo').nick_name

        var random = Math.floor(Math.random() * 3);
        console.log(res)

        // 来自页面内转发按钮
        if (res.from === 'button') {
            // console.log(res)
            // 来自页面内转发按钮
            if (res.target.dataset.hot == 1) {
                if (that.data.hotmarks[res.target.dataset.index].photos[0]) {
                    return {
                        title: '我关注' + that.data.hotmarks[res.target.dataset.index].username + ',' + that.data.hotmarks[res.target.dataset.index].intro,
                        path: "pages/cruisedetails/cruisedetails?account_id=" + uid + "&id=" + res.target.id,
                        imageUrl: that.data.hotmarks[res.target.dataset.index].photos[0],
                    }
                } else {
                    return {
                        title: '我关注' + that.data.hotmarks[res.target.dataset.index].username + ',' + that.data.hotmarks[res.target.dataset.index].intro,
                        path: "pages/cruisedetails/cruisedetails?account_id=" + uid + "&id=" + res.target.id,
                        // imageUrl: that.data.hotmarks[res.target.dataset.index].photos[0],
                        imageUrl: '../res/wxshare.jpg',
                    }
                }

            }
            // console.log(that.data.hotmarks[res.target.dataset.index].intro)
            if (res.target.dataset.hot == 4) {
                if (that.data.newmarks[res.target.dataset.index].photos[0]) {
                    return {
                        title: '我关注' + that.data.newmarks[res.target.dataset.index].username + ',' + that.data.newmarks[res.target.dataset.index].intro,
                        path: "pages/cruisedetails/cruisedetails?account_id=" + uid + "&id=" + res.target.id + "&type=mark",
                        imageUrl: that.data.newmarks[res.target.dataset.index].photos[0],
                    }
                } else {
                    return {
                        title: '我关注' + that.data.newmarks[res.target.dataset.index].username + ',' + that.data.newmarks[res.target.dataset.index].intro,
                        path: "pages/cruisedetails/cruisedetails?account_id=" + uid + "&id=" + res.target.id + "&type=mark",
                        // imageUrl: that.data.newmarks[res.target.dataset.index].photos[0],
                        imageUrl: '../res/wxshare.jpg',
                    }
                }

            }
            // console.log(that.data.newmarks[res.target.dataset.index].intro)
        } else {
            return {
                // title: nickname + " " + that.data.sharearray[random],
                title: '发现一个好用的巡河神器，一起来看看',
                path: "pages/newpage/newpage?account_id=" + uid,
                // imageUrl: '../res/wxshare.jpg',
            }
        }
    },
    onReady: function() {},
    //下拉刷新
    onPullDownRefresh: function () {
        // 显示顶部刷新图标
        wx.showLoading({
            title: '刷新中',
          });
        let that = this
        that.getindexinfo(that.data.province,that.data.city)
        setTimeout(function(){
            wx.hideLoading()
            wx.stopPullDownRefresh()
          },2000)
      },
    onPageScroll: function(e) {
        if (e.scrollTop > 80) {
            this.setData({
                floorstatus: true
            });
        } else {
            this.setData({
                floorstatus: false
            });
        }
    },
    goTop: function(e) { // 一键回到顶部
        if (wx.pageScrollTo) {
            wx.pageScrollTo({
                scrollTop: 0
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    }
})